package com.gome.feitian.atp.rest.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yangpengfei on 2016/3/4.
 */
public class PageWorker {
    private static Logger logger = LoggerFactory.getLogger(PageWorker.class);

    //根据长度+总数切割成数组，例如[a,b,c],100，切割结果为[1-33,34-66,67-100]
    public static List<int[]> getSpitByIps(String[] ips, int total) {
        int duo = total % ips.length;//除不尽多出来的数
        int step = total / ips.length;//集合长度，即分块数量
        System.out.println(duo);
        System.out.println(step);
        System.out.println();

        List arr = new ArrayList();
        int index = 1;
        int a = 0;
        int b = 0;
        do {
            a = (index - 1) * step + 1;
            b = index * step;
            if (b > total) {
                break;
            }
            arr.add(new int[]{a, b});
            index++;
        } while (true);

        //将集合最后一项补满
        if (duo > 0) {
            int[] rr = (int[]) arr.get(arr.size() - 1);
            //rr[1] += duo;//方法1
            rr[1] = total;//方法2
        }

        for (int i = 0; i < arr.size(); i++) {
            int[] rr = (int[]) arr.get(i);
            logger.info(rr[0] + "," + rr[1]);
        }
        return arr;
    }

    /**
     * @param op     匹配的url，例如http://{0}/atp
     * @param ips    Ip和端口，用于对位服务器
     * @param splits 执行的段
     * @param worker 具体执行的方法
     */
    public static void mutiExecutor(String op, String[] ips, List<int[]> splits, final HttpWorker worker) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(splits.size());
        try {
            for (int i = 0; i < splits.size(); i++) {
                final int[] spits = splits.get(i);
                final String url = op.replace("{0}", ips[i]);
                System.out.println(url);
                exec.execute(new Thread() {
                    public void run() {
                        worker.exec(spits[0], spits[1], url);
                    }
                });
            }

            //该方法在加入线程队列的线程执行完之前不会执行。
            exec.shutdown();
            while (true) {
                //当shutdown()或者shutdownNow()执行了之后才会执行，并返回true。
                if (exec.isTerminated()) {
                    logger.info("该批次执行完成！");
                    break;
                }
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            logger.error("执行失败", e);
            throw e;
        }
    }
}

